<template>
  <div class="correlation-obj-select-box">
    <!-- 物料 -->
    <biz-remote-select 
      v-if="relType === 2" 
      :placeholder="$t('common.placeholder.select')" 
      popper-class="correlation-obj-custom-select"
      v-model="relObj" 
      :cleared="true" 
      :remote-method="fetchMaterial" 
      @input="changeHandle" >
      <div class="obj-material-select" slot="option" slot-scope="{ option }">
        <template v-if="option.name && !loading">
          <p>
            {{ $t('common.form.preview.materialReturn.tableLabel1') }}：<span>{{ option.name }}</span>
          </p>
          <p>
            {{ $t('common.fields.materielNo.displayName') }}：<span>{{ option.sn }}</span>
          </p>
          <p>
            {{ $t('common.form.preview.materialReturn.tableLabel4') }}：<span>{{ option.property }}</span>
          </p>
        </template>
        <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
      </div>
    </biz-remote-select>

    <!-- 备件 -->
    <biz-remote-select v-else-if="relType === 3" :placeholder="$t('common.placeholder.select')" v-model="relObj" :cleared="true" :remote-method="fetchSparepartList" @input="changeHandle">
      <div class="obj-material-select" slot="option" slot-scope="{ option }">
        <template v-if="option.name && !loading">
          <p>{{ $t('common.base.name') }}：{{ option.name }}</p>
          <p>{{ $t('common.base.serialNumber') }}：{{ option.serialNumber }}</p>
          <p>{{ $t('common.part.specifications') }}：{{ option.standard }}</p>
          <p v-if="option.description">{{ $t('common.base.explain') }}：{{ option.description }}</p>
        </template>
        <p class="no_empty" v-else>{{ loading ? $t('common.base.loading') : $t('common.base.tip.noData') }}</p>
      </div>
    </biz-remote-select>

    <!-- 产品 -->
    <!-- <el-cascader
      v-else
      ref="cascaderProduct"
      v-model="relObj"
      :options="productData"
      clearable
      :style="{width: '100%'}"
      filterable
      collapse-tags
      :before-filter="beforeFilter"
      :props="cascadeProps"
      @change="changeHandle"
      @visible-change="regionMenuChange"
    ></el-cascader> -->

    <CascaderPower ref="cascaderPower" :value="relObj" @input="(value)=>{relObj = value;changeHandle()}" v-else :root-options="rootOptions"></CascaderPower>
  </div>
</template>

<script>
// 产品接口
import { queryCatalogTree, searchProductByTreeModeListPage } from '@src/api/ProductV2Api';
// 物料列表
import { getMaterialList } from '@src/api/WareHouseApi';

import SearchMaterialSelect from '@src/component/form/common/warehouse/SearchMaterialSelect.vue';
import _ from 'lodash';
import CascaderPower from '@src/component/compomentV2/cascaderPower/index.vue';
import { initBaseSearchListItem } from '@src/component/compomentV2/cascaderPower/common';

export default {
  // 故障对象选择具体对象
  name: 'CorrelationObjSelect',
  components: {
    [SearchMaterialSelect.name]: SearchMaterialSelect,
    CascaderPower,
  },
  data() {
    return {
      rootOptions: { collapseTags: true, labelKey: 'catalogName', keyKey: 'id', haveChildKey: 'isExistChild', labelKeySearch: 'catalogName', keyKeySearch: 'id', keyArrKeySearch:'parentIdList', getListFnc: this.getListFnc },
      // 记录产品对象的数据
      productData: [],
      loading: false,
      cascadeProps: {
        value: 'id',
        label: 'name',
        children: 'tasks',
        multiple: true,
        checkStrictly: true,
      },
    };
  },

  props: {
    // 关联类型（0:默认值-标签 1:产品 2:物料 3:备件）
    relType: {
      type: Number,
      default: 0,
    },

    value: {
      type: Array,
      default: () => {
        return [];
      },
    },

    collapseTag: {
      type: Boolean,
      default: false,
    },
    taskProductId: {
      type: Array,
      default: () => ([]),
    }
  },
  watch: {
    taskProductId: {
      immediate: true,
      deep: true,
      handler(value) {
        if(value && value.length) {
          const params = {
            productIdList: value,
            keyword:'',
            pageNum: 1,
            pageSize: 20
          }
          this.getProductByTreeModeListPage(params);
        }
      },
    },
  },
  computed: {
    // 选中的关联对象id
    relObj: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },

  mounted() {
    if (this.relType === 1) {
      this.clearCascader();
      this.beforeFilter('');
    }

    // console.log(loopPathArr([1,2,3], [1,2]), '321')
  },

  methods: {
    getProductByTreeModeListPage(params) {
      try {
        searchProductByTreeModeListPage(params).then(res=>{
          const {success, result} = res
          if(success) {
            let list_ = initBaseSearchListItem(result.list, this.rootOptions);
            this.$refs.cascaderPower.choosedData = list_ || [];
          }
        })
      } catch(error){
        console.log(error)
      }
    },
    
    // 父组件调用，获取id和name集合
    getIdAndName() {
      let data = [];
      if (this.relType == 2 || this.relType === 3) {
        data = this.value.map(item => {
          let { id, name } = item;
          return {
            relObjId: id,
            relObjName: name,
          };
        });
      } else {
        data = this.value;
      }
      return data;
    },

    changeHandle(e) {
      if (this.$listeners.relIdChange) {
        this.$emit('relIdChange', this.relObj);
      }
    },
    /**
     * @description 搜索物料
     */
    async fetchMaterial(params) {
      this.loading = true;
      try {
        let res = await getMaterialList({ ...params });
        this.loading = false;
        if (!res.success) return;
        res.data.list = res.data.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item,
          };
        });

        return res.data;
      } catch (error) {
        this.loading = false;
        console.warn('fetchMaterial -> error', error);
      } finally {
        this.loading = false;
      }
    },
    // 搜索备件
    async searchSparepart(params = {}) {
      return this.fetchSparepartList(params);
    },
    // 获取备件
    async fetchSparepartList(selectParams) {
      let params = {
        keyWord: selectParams.keyword,
        pageNum: selectParams.pageNum,
        pageSize: 10,
      };

      try {
        let res = await this.$http.post('/partV2/category/listData', params);
        if (!res || !res.list) return;

        res.list = res.list.map(item =>
          Object.freeze({
            label: item?.name || '',
            value: item?.id || '',
            ...item,
          })
        );

        res.pageNum = params.page;

        return res;
      } catch (error) {
        console.warn('etchSparepartList -> error', error);
      }
    },
    // 获取产品类型
    async beforeFilter(value) {
      try {
        const { code, message, result } = await queryCatalogTree({ keyWord: value });
        if (code === 0) {
          this.deleteEmpty(result);
          this.productData = result;
        } else {
          this.$platform.notification({
            type: 'error',
            message,
          });
        }
      } catch (err) {
        console.error(err);
      }

      return false;
    },
    // 删除空子集
    deleteEmpty(list) {
      list.forEach(item => {
        if (!item?.tasks?.length) {
          delete item.tasks;
        } else {
          this.deleteEmpty(item.tasks);
        }
      });
    },
    // 清空级联下拉数据
    clearCascader() {
      this.productData = [];
      // this.$refs.cascaderProduct.$refs.panel.activePath = [];
    },
    regionMenuChange(boolean) {
      // 聚焦时
      if (boolean && !this.relObj.length) {
        this.clearCascader();
        this.beforeFilter('');
      }
    },
    getListFnc(param) {
      const { params  } = param;
      delete param.params
      const { key, keyword } = params
      let params_ = {
        ...param,
        parentId: key,
        keyword,
      };
      return searchProductByTreeModeListPage(params_);
      const list = [];
      for (let i = 0; i < 10; i++) {
        list.push({
          key: i,
          label: `ces${i}`,
          haveChild: true,
        });
      }
      return Promise.resolve({
        status: 0,
        data: {
          pageNum: 1,
          pageSize: 20,
          size: 1,
          startRow: 1,
          endRow: 0,
          total: 5,
          pages: 1,
          list,
          prePage: 0,
          nextPage: 0,
          isFirstPage: true,
          isLastPage: true,
          hasPreviousPage: false,
          hasNextPage: false,
          navigatePages: 0,
          navigatepageNums: null,
          navigateFirstPage: 0,
          navigateLastPage: 0,
          firstPage: 0,
          lastPage: 0,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.correlation-obj-select-box {
  ::v-deep .el-cascader__tags {
    left: -3px;
  }
}
.el-form-item__label {
  margin: 0;
}
.obj-material-select {
  padding: 8px 5px 0 0;
  overflow: hidden;
  width: 100%;
  line-height: 14px;
}
</style>
<style lang="scss">
.correlation-obj-custom-select {
  min-height: 266px;
  width: 428px;
  .el-select-dropdown__empty {
    margin-top: 100px;
  }
}
</style>
